//
//  SYPicturePickVC.swift
//  SYWeibo
//
//  Created by Saya on 16/4/16.
//  Copyright © 2016年 黄金果. All rights reserved.
//
/**
使用hmImagePicker需要添加变量
    var selectAssete:[PHAsset] = [PHAsset]()

创建的时候需要设置
//使用HMImagePicker一定要设置目标的size  和  最大张数
imagePicVC.targetSize = CGSize(width: 600, height: 600)
imagePicVC.maxPickerCount = maxSelectCount

在代理方法中将
self.selectAssete = selectedAssets!

在删除按钮的方法中需要
selectAssete.removeAtIndex(indexPathForCell.item)

*/

import UIKit
import HMImagePicker

private let itemBtItem:CGFloat = 5
private let numOfItemInRow:CGFloat = 4
private let itemWidth :CGFloat = (screenWidth - (numOfItemInRow-1) * itemBtItem - 2 * marginForCell) / numOfItemInRow
private let identy:String = "cell"
private let maxSelectCount:Int = 2

class SYPicturePickVC: UICollectionViewController {
    
    var imageList:[UIImage] = [UIImage]()
    var selectAssete:[PHAsset] = [PHAsset]()
    
    init(){
        let layout = UICollectionViewFlowLayout()
        layout.minimumInteritemSpacing = itemBtItem
        layout.minimumLineSpacing = itemBtItem
        layout.sectionInset = UIEdgeInsetsMake(marginForCell, marginForCell, 0, marginForCell)
        layout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        super.init(collectionViewLayout: layout)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        collectionView?.backgroundColor = UIColor(white: 0.99, alpha: 1)
        collectionView?.registerClass(SYPicturePickCell.self, forCellWithReuseIdentifier: identy)
    }
    
    

}

//数据源方法
extension SYPicturePickVC{
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        let delate = imageList.count >= maxSelectCount ? 0 : 1
        return imageList.count + delate
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let item = collectionView.dequeueReusableCellWithReuseIdentifier(identy, forIndexPath: indexPath) as! SYPicturePickCell
        item.backgroundColor = randomColor()
        
        if imageList.count == indexPath.item{
            //这种情况下什么也不做,因为上面+1,所以会出现错误的情况
            item.pickedImg = nil
            item.addBtn.enabled = true
        }else{
            item.pickedImg = imageList[indexPath.item]
            item.addBtn.enabled = false
        }
        item.delegate = self
        return item
    }
}

//delegate
extension SYPicturePickVC:SYPicturePickCellDelegate,HMImagePickerControllerDelegate{
    func userWilLAddImage() {
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary){
            //使用系统的picker完成,单图的选择
//            let imagePicVC = UIImagePickerController()
//            imagePicVC.delegate = self
//            presentViewController(imagePicVC, animated: true, completion: nil)
            //使用HMImagePicker
            let imagePicVC:HMImagePickerController = HMImagePickerController(selectedAssets: selectAssete)
            imagePicVC.pickerDelegate = self
            //使用HMImagePicker一定要设置目标的size  和  最大张数
            imagePicVC.targetSize = CGSize(width: 600, height: 600)
            imagePicVC.maxPickerCount = maxSelectCount
            presentViewController(imagePicVC, animated: true, completion: nil)
        }
        
    }
    
    func userWillDeleteImage(cell:UICollectionViewCell) {
        //uicollectionViewCell有一个方法,可以通过cell获取indexPath
        if let indexPathForCell = collectionView?.indexPathForCell(cell){
            imageList.removeAtIndex(indexPathForCell.item)
            //如果使用hmiagePicker
            selectAssete.removeAtIndex(indexPathForCell.item)
            collectionView?.reloadData()
        }
    }
    
    //该方法为使用系统的picker选择图片
    
//    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
////        print(editingInfo)
//        
//        imageList.append(image)
//        collectionView?.reloadData()
//        dismissViewControllerAnimated(true, completion: nil)
//    }
    
    //使用HMImagePicker实现代理方法
    func imagePickerController(picker: HMImagePickerController, didFinishSelectedImages images: [UIImage], selectedAssets: [PHAsset]?) {
        self.imageList = images
        self.selectAssete = selectedAssets!
        collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
    }
}

class SYPicturePickCell :UICollectionViewCell{
    
    var pickedImg:UIImage?{
        didSet{
            addBtn.setImage(pickedImg, forState: .Normal)
//            addBtn.enabled = pickedImg == nil
            deleteBtn.hidden = pickedImg == nil
        }
    }
    
    //delegate
    var delegate:SYPicturePickCellDelegate?

    @objc func addBtnDidClick(sender:UIButton){
        print("user did click add button")
        delegate?.userWilLAddImage?()
    }
    
    @objc func deleteBtnDidClick(sender:UIButton){
        print("user did click delete button")
        delegate?.userWillDeleteImage?(self)
    }
    
    private func setUpUI(){
        addSubview(addBtn)
        addSubview(deleteBtn)
        
        addBtn.snp_makeConstraints { (make) -> Void in
            make.edges.equalTo(self)
        }
        deleteBtn.snp_makeConstraints { (make) -> Void in
            make.top.right.equalTo(self)
        }
    }
    
    private lazy var addBtn:UIButton = {
        let addButton = UIButton()
        addButton.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: .Normal)
        addButton.setBackgroundImage(UIImage(named: "compose_pic_add_highlighted"), forState: .Highlighted)
        addButton.addTarget(self, action: "addBtnDidClick:", forControlEvents: .TouchUpInside)
        addButton.sizeToFit()
        addButton.adjustsImageWhenDisabled = false
        return addButton
    }()
    
    private lazy var deleteBtn:UIButton = {
        let delButton = UIButton()
        delButton.setBackgroundImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        delButton.addTarget(self, action: "deleteBtnDidClick:", forControlEvents: .TouchUpInside)
        delButton.sizeToFit()
        delButton.hidden = true
        return delButton
    }()
    
    //控件自定义的入口,init方法,外界会调用的初始化方法
    override init(frame: CGRect) {
        super.init(frame: frame)
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
}


@objc protocol SYPicturePickCellDelegate:NSObjectProtocol{
    optional func userWilLAddImage()
    optional func userWillDeleteImage(cell:UICollectionViewCell)
}























